package cn.itcast.controller.company;

import cn.itcast.controller.BaseController;
import cn.itcast.domain.company.Company;
import cn.itcast.service.company.CompanyService;
import cn.itcast.vo.PageBean;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/company")
@Component
@Service
@Repository
public class CompanyController extends BaseController {


    @Reference
    private CompanyService companyService;

    @RequestMapping(value = "/list",name = "分页展示企业列表数据")
//    用户在访问/company/list.do方法时必须要有“企业管理”权限才行  会进入到自定义的Realm的授权方法中判断是否有相关权限
    @RequiresPermissions("企业管理")
    public String findAll(@RequestParam(value = "page",required=false,defaultValue ="1" )Integer pageNum,
                          @RequestParam(required=false,defaultValue ="2" )Integer pageSize){
//        List<Company> list = companyService.findAll();
//        PageBean pageBean = companyService.findPage(pageNum,pageSize);
        PageInfo pageInfo = companyService.findPage(pageNum,pageSize);
        request.setAttribute("page",pageInfo); //这个“page” 固定不能修改 因为页面上要的就是page这个变量名
        return "company/company-list";
    }
    @RequestMapping(value = "/toAdd",name = "进入到新增企业的页面")
    public String toAdd(){
        return "company/company-add";
    }


    @RequestMapping(value = "/edit",name = "保存企业的方法")
    public String edit(Company company){
//        判断company中id是否为空，如果为空就是新增反之就是修改
        if(StringUtils.isEmpty(company.getId())){//如果为空
            String id = UUID.randomUUID().toString();
            company.setId(id);
            companyService.save(company);
        }else{
            companyService.update(company);
        }
        return "redirect:/company/list.do"; //一定要重定向到列表页面
    }

    @RequestMapping(value = "/toUpdate",name = "进入到修改企业的页面")
    public String toUpdate(String id){
        Company company = companyService.findById(id);
        request.setAttribute("company",company);
        return "company/company-add";
    }

    @RequestMapping(value = "/delete",name = "删除企业的方法")
    public String delete(String id){
        companyService.delete(id);
        return "redirect:/company/list.do"; //一定要重定向到列表页面
    }
}
